import re

from django.shortcuts import render
from user import models
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from django.db.models import Q
from utils.tooljwt import mean
import re
import random
from utils.smscode import sms
import json
from utils.redis import redistool
# Create your views here.

class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username',"")
        password = request.data.get('password',"")
        if not username or not password:
            return Response({"code":400,"msg":"用户名或密码不能为空"})
        info=models.User.objects.filter(Q(username=username)|Q(iphone=username)|Q(email=username),isdel=False).first()
        if not info:
            return Response({"code":400,"msg":"账号不存在"})
        if info.password!=password:
            return Response({"code":400,"msg":"密码错误"})
        token=mean.gettoken({"id":info.id})
        return Response({"code":200,"msg":"登录成功","data":{"token":token,"userid":info.id}})
class SendCode(APIView):
    def post(self, request):
        # 1.获取手机号
        phone = request.query_params.get('phone', '')
        # 2.验证手机格式 写一个手机号的正则
        result = re.match(r'^1[3-9]\d{9}$', phone)
        if not result:
            return Response({"code": 400, "msg": "手机号格式不正确"})
        if redistool.get_code(phone):
            return Response({"code": 400, "msg": "验证码已发送,请稍后重试"})
        code = str(random.randint(1000, 9999))
        res = json.loads(sms.send(phone, code))
        if(res["statusCode"]=="000000"):
            redistool.set_code(phone,code)
            return Response({"code": 200, "msg": "验证码发送成功"})
        else:
            return Response({"code": 400, "msg": "验证码发送失败"})
class Login(APIView):
    def post(self, request):
    # 1获取手机号和验证码
        phone = request.data.get('phone', '')
        code = request.data.get('code', '')
        if not phone or not code:
            return Response({"code": 400, "msg": "手机号或验证码不能为空"})
        # 2.验证手机号格式
        result = re.match(r'^1[3-9]\d{9}$', phone)
        if not result:
            return Response({"code": 400, "msg": "手机号格式不正确"})
      # 3.根据手机号去redis中获取验证码
        rediscode = redistool.get_code(phone)
        if rediscode != code:
            return Response({"code": 400, "msg": "验证码错误"})
        # 4.验证码成功后 登陆成功返回token
        info = models.User.objects.filter(iphone=phone).first()
        if not info:
            info = models.User.objects.create(iphone=phone)
#         根据info模型对象生成token
        token = mean.gettoken({"id": info.id})
        return Response({"code": 200, "msg": "登陆成功", "data": {"token": token, "userid": info.id}})



